package com.weimob.mcloud.wechatwork.customer.mq;

import com.alibaba.fastjson.JSON;
import com.ctrip.framework.apollo.spring.annotation.ApolloJsonValue;
import com.weimob.artemis.client.consumer.model.ConsumerRecord;
import com.weimob.artemis.client.consumer.model.MessageResult;
import com.weimob.artemis.client.spring.annotation.ArtemisConsumerListener;
import com.weimob.artemis.client.spring.annotation.Subscribe;
import com.weimob.mcloud.wechatwork.customer.domain.ArtemisConstant;
import com.weimob.mcloud.wechatwork.customer.domain.ExternalUserChangeInfo;
import com.weimob.mcloud.wechatwork.customer.domain.ExternalUserHistoryInfo;
import com.weimob.mcloud.wechatwork.customer.mq.handler.externaluser.HistoryCorpExternalUserSyncHandler;
import com.weimob.mcloud.wechatwork.customer.service.user.enums.YesOrNoEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 商家第一次用企微助手，将其企业微信下的外部联系人数据，同步到微盟DB进行初始化
 */
@Slf4j
@Component
public class CorpwxHistoryExternalUserConsumer {

    @Autowired
    private HistoryCorpExternalUserSyncHandler historyCorpExternalUserSyncHandler;

    @ApolloJsonValue("${history.customer.sync.filter.corpIds:[]}")
    private List<String> filterCorpIds;

    /**
     * 商家第一次用企微助手，将其企业微信下的外部联系人数据，同步到微盟DB进行初始化
     */
    @ArtemisConsumerListener(
            value = @Subscribe(topic = ArtemisConstant.Topic.WECHATWORK_BOS_SYNC_EXTERNALCONTACT, user = ArtemisConstant.USER), interval = 50)
    public void syncCorpWxExternalContactConsumer(MessageResult result) {
        // 1.从消息里拿出要同步的外部联系人数据
        List<ConsumerRecord> records = result.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return;
        }


        // 2.遍历外部联系人数据
        for (ConsumerRecord consumerRecord : records) {
            log.info("新中台消费历史外部联系人message：{}", JSON.toJSONString(consumerRecord));

            try {
                // 3.外部联系人数据json转Object ExternalUserHistoryInfo-->ExternalUserChangeInfo
                ExternalUserHistoryInfo externalUserHistoryInfo = JSON.parseObject(consumerRecord.getValue().toString(), ExternalUserHistoryInfo.class);
                if (null == externalUserHistoryInfo) {
                    log.error("客户历史数据初始化失败, 消息体转换异常");
                    continue;
                }

                //如果openCorpId不为空，则为腾讯id升级之后的店铺，企微助手这边直接取密文数据
                String openCorpId = externalUserHistoryInfo.getOpenCorpId();
                if (StringUtils.isNotBlank(openCorpId)) {

                    //密文处理逻辑过滤，过滤指定corpId历史数据同步,临时解决客户频繁同步历史数据造成的积压
                    if (CollectionUtils.isNotEmpty(filterCorpIds) && filterCorpIds.contains(openCorpId)) {
                        log.info("过滤指定corpId历史数据同步, corpId:{}", openCorpId);
                        continue;
                    }

                    ExternalUserChangeInfo externalUserChangeInfo = new ExternalUserChangeInfo();
                    externalUserChangeInfo.setExternalUserID(externalUserHistoryInfo.getOpenExternalUserid());
                    externalUserChangeInfo.setToUserName(externalUserHistoryInfo.getOpenCorpId());
                    externalUserChangeInfo.setBosId(externalUserHistoryInfo.getBosId());
                    externalUserChangeInfo.setCustomerWid(externalUserHistoryInfo.getWid());
                    externalUserChangeInfo.setHistoryCustomerSync(YesOrNoEnum.YES.getCode());

                    historyCorpExternalUserSyncHandler.handleCorpExternalUser(externalUserChangeInfo);

                } else {
                    String corpId = externalUserHistoryInfo.getCorpId();
                    if (StringUtils.isBlank(corpId)) {
                        log.error("客户历史数据同步失败, corpId为空");
                        continue;
                    }

                    //明文处理逻辑过滤，过滤指定corpId历史数据同步,临时解决客户频繁同步历史数据造成的积压
                    if (CollectionUtils.isNotEmpty(filterCorpIds) && filterCorpIds.contains(corpId)) {
                        log.info("过滤指定corpId历史数据同步, corpId:{}", corpId);
                        continue;
                    }

                    ExternalUserChangeInfo externalUserChangeInfo = new ExternalUserChangeInfo();
                    externalUserChangeInfo.setExternalUserID(externalUserHistoryInfo.getExternalUserId());
                    externalUserChangeInfo.setToUserName(externalUserHistoryInfo.getCorpId());
                    externalUserChangeInfo.setBosId(externalUserHistoryInfo.getBosId());
                    externalUserChangeInfo.setCustomerWid(externalUserHistoryInfo.getWid());
                    externalUserChangeInfo.setHistoryCustomerSync(YesOrNoEnum.YES.getCode());

                    historyCorpExternalUserSyncHandler.handleCorpExternalUser(externalUserChangeInfo);
                }
            }
            catch (Exception e) {
                log.warn("消费历史外部联系人 Artemis数据处理失败. message:{}", e.getMessage(), e);
            }
        }
    }
}
